<template>
  <div class="bgc-default" v-loading.fullscreen="listLoading" element-loading-text="加载中">
    <!-- 导航块 -->
    <div class="top-nav">
      <template v-for="(item, index) of topNavBar">
        <div :key="index" class="nav-item" :class="{'nav-active' : topNavBaroIndex === index}"
          @click="goTarget('#' + item.target, index)">{{item.name}}</div>
      </template>
    </div>
    <div class="circle-x-tab pad-l-20 pad-r-20 mar-t-20">
      <template v-if="baseDataPreFlag">
        <!-- 基本信息 -->
        <goods-info id="base-info"
          ref="goodsInfoRef"
          :fromListPage="fromListPage"
          :goodsObj="goodsObj"
          @addVaildShow="addVaildShow"
        >
        </goods-info>

        <!-- 渠道设置 -->
        <goods-channel id="channel-set"
          ref="goodsChannelRef"
          :fromListPage="fromListPage"
          :goodsObj="goodsObj"
          @addVaildShow="addVaildShow"
        >
        </goods-channel>

        <!-- 规格信息 -->
        <goods-sku id="sku-set"
          ref="goodsSkuRef"
          :fromListPage="fromListPage"
          :goodsId="goodsId"
          :goodsObj="goodsObj"
          @addVaildShow="addVaildShow"
        >
        </goods-sku>

        <!-- 佣金设置 -->
        <goods-commission id="commission-set"
          ref="goodsCommissionRef"
          v-show="fromListPage == 30"
          :fromListPage="fromListPage"
          :goodsObj="goodsObj"
          @addVaildShow="addVaildShow"
        >
        </goods-commission>

        <!-- 参数设置 -->
        <goods-parameter id="params-set"
          ref="goodsParameterRef"
          :fromListPage="fromListPage"
          :goodsObj="goodsObj"
          @addVaildShow="addVaildShow"
        >
        </goods-parameter>

        <!-- 商品详情 -->
        <goods-detail id="goods-detail"
          ref="goodsDetailRef"
          class="mar-r-30"
          :fromListPage="fromListPage"
          :goodsObj="goodsObj"
          @addVaildShow="addVaildShow"
        >
        </goods-detail>

        <!-- 其他设置 -->
        <goods-other id="other-set"
          ref="goodsOtherRef"
          :fromListPage="fromListPage"
          :goodsObj="goodsObj"
          @addVaildShow="addVaildShow"
        >
        </goods-other>
      </template>
    </div>

    <template v-if="validShowList.filter(item => item.validateMessage).length > 0">
      <div class="valid-show-box">
        <div class="box-head">错误信息（{{ validShowList.filter(item => item.validateMessage).length }}）</div>
        <div class="box-body">
          <el-row v-for="(item, index) in validShowList.filter(item => item.validateMessage)" :key="index" type="flex" align="middle">
            <template v-if="item.validateMessage">
              <el-col :span="16">
                <el-tooltip class="item" effect="light" :content="item.label + item.validateMessage" placement="top">
                  <div class="line-1">{{ index + 1 }}、{{ item.label }}{{ item.validateMessage }}</div>
                </el-tooltip>
              </el-col>
              <el-col :span="8" align="right">
                <el-button type="text" size="medium" class="font-red" @click="doJump(item.$el)">查看</el-button>
              </el-col>
            </template>
          </el-row>
        </div>
      </div>
    </template>

    <div class="bottom-bar">
      <el-button class="mar-l-30" type="primary" @click="doSave">保存</el-button>
    </div>

    <!-- 结果dialog -->
    <el-dialog :visible.sync="resultVisible"
      width="500px"
      top="15%"
      :center="true"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :show-close="false">

      <el-row type="flex">
        <el-col :span="4" align="center">
          <i class="el-icon-success font-green font-30"></i>
        </el-col>
        <el-col :span="18">
          <div><span class="font-22">保存成功</span></div>
          <div class="font-gray font-16 mar-t-10">
            <span>商品保存成功，数据已更新</span>
          </div>
        </el-col>
      </el-row>

      <!-- 底部按钮 -->
      <div class="mar-t-30" style="text-align: right">
        <el-button @click="doClose">关闭页面</el-button>
        <el-button @click="doSeeDetail">查看商品</el-button>
        <el-button type="primary" @click="doAdd">新建商品</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { getByEnterpriseId } from '@/api/user/enterprise'
  import { getDictByGroupName } from '@/api/common/common'
  import { saveGoods, getGoodsDetail } from '@/api/goods/goods'
  import { getDetailByConvertGoods } from '@/api/third/thirdGoodsSyncHistory'

  import elDragDialog from '@/directive/el-dragDialog'
  import goodsInfo from './components/goods-info'
  import goodsChannel from './components/goods-channel'
  import goodsSku from './components/goods-sku'
  import goodsOther from './components/goods-other'
  import goodsCommission from './components/goods-commission'
  import goodsParameter from './components/goods-parameter'
  import goodsDetail from './components/goods-detail'

  export default {
    components: {
      goodsInfo,
      goodsChannel,
      goodsSku,
      goodsOther,
      goodsCommission,
      goodsParameter,
      goodsDetail
    },
    directives: {
      elDragDialog
    },
    data() {
      return {
        // 基础数据准备flag
        baseDataPreFlag: false,
        // 商品id
        goodsId: '',
        // 同步商品记录id
        goodsSyncHistoryId: '',
        // 详情模板id
        detailTemplateId: null,
        // 主播素材模板id
        anchorTemplateId: null,
        // 跳转源 30：零售 31：批发
        fromListPage: 30,
        goodsSource: '0',
        // 商品对象
        goodsObj: {},
        // 验证列表
        validShowList: [],
        // 导航栏
        topNavBar: [
          { name: '基本信息', target: 'base-info' },
          { name: '渠道设置', target: 'channel-set' },
          { name: '规格信息', target: 'sku-set' },
          { name: '商品佣金', target: 'commission-set' },
          { name: '参数设置', target: 'params-set' },
          { name: '商品详情', target: 'goods-detail' },
          { name: '其他设置', target: 'other-set' }
        ],
        // 结果表单
        resultForm: {
          goodsId: ''
        },
        // 导航位置
        topNavBaroIndex: 0,
        listLoading: false,
        resultVisible: false
      }
    },
    // 组件销毁
    beforeDestroy() {
      window.removeEventListener('mousewheel', this.getDomTop)
      this.$bus.$off('ComponentTemplate.bindTemplateId')
    },
    // 初始化页面
    created() {
      const queryParams = this.getCurrentPage().query
      this.goodsId = !queryParams.goodsId ? '' : queryParams.goodsId
      this.goodsSyncHistoryId = !queryParams.goodsSyncHistoryId ? '' : queryParams.goodsSyncHistoryId
      this.fromListPage = !queryParams.fromListPage ? 30 : queryParams.fromListPage * 1
    },
    mounted() {
      this.initBaseData()
    },
    methods: {
      // 初始化基础信息
      initBaseData() {
        // 清空
        this.$store.dispatch('setEnterpriseConfig', {})
        const enterpriseId = this.getEnterpriseId()
        // 获取企业配置
        const getEnterpriseConfigFx = new Promise((resolve, reject) => {
          getByEnterpriseId(enterpriseId).then((response) => {
            if (response.isError) {
              reject('fail')
            } else {
              resolve(response.data)
            }
          })
        })
        // 获取数据字典
        const getDictFx = new Promise((resolve, reject) => {
          getDictByGroupName('ProjectGoodsDTO').then(response => {
            if (response.isError) {
              reject('fail')
            } else {
              resolve(response.data)
            }
          })
        })
        // 获取商品详情
        const goodsInfoFx = new Promise((resolve, reject) => {
          if (!this.goodsId && !this.goodsSyncHistoryId) {
            resolve(null)
            return
          }
          if (this.goodsSyncHistoryId) {
            getDetailByConvertGoods(this.goodsSyncHistoryId).then((response) => {
              if (response.isError) {
                reject('fail')
              } else {
                resolve(response.data)
              }
            })
          } else {
            getGoodsDetail({ goodsId: this.goodsId }).then((response) => {
              if (response.isError) {
                reject('fail')
              } else {
                resolve(response.data)
              }
            })
          }
        })

        this.listLoading = true
        Promise.all([getEnterpriseConfigFx, getDictFx, goodsInfoFx]).then((result) => {
          this.baseDataPreFlag = true
          const strArr = Object.values(result).filter(val => {
            return typeof (val) === 'string'
          })
          // 存在调用异常
          if (strArr.indexOf('fail') !== -1) {
            this.$message({ type: 'error', message: '商品页异常' })
            this.listLoading = false
            return
          }
          this.$store.dispatch('setEnterpriseConfig', result[0])
          this.$store.dispatch('setDict', result[1])
          this.goodsObj = result[2] ? result[2] : {}

          this.$nextTick(function() {
            this.listLoading = false
            const queryParams = this.getCurrentPage().query
            if (queryParams.active) {
              this.goTarget(`#${this.topNavBar[queryParams.active]['target']}`, queryParams.active)
            }
            for (let i = 0; i < this.topNavBar.length; i++) {
              const dom = document.getElementById(`${this.topNavBar[i]['target']}`)
              this.$set(this.topNavBar[i], 'top', dom.offsetTop)
              this.$set(this.topNavBar[i], 'h', dom.clientHeight)
            }
          })

          // 监听
          const that = this
          window.addEventListener('mousewheel', that.getDomTop)

          that.$bus.$on('ComponentTemplate.bindTemplateId', function(data) {
            if (data.componentType === 'componentAnchorDetail') {
              that.anchorTemplateId = data.templateId
            } else {
              that.detailTemplateId = data.templateId
            }
            if (data.needSaveGoods) {
              that.doSaveAfterHandle()
            }
          })
        })
      },
      // 鼠标滚动导航定位事件
      getDomTop() {
        const that = this
        const scroll = document.documentElement.scrollTop || document.body.scrollTop
        const windowHeight = document.documentElement.clientHeight || document.body.clientHeight
        const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
        for (let i = 0; i < that.topNavBar.length; i++) {
          const dom_id = `${that.topNavBar[i]['target']}`.trim()
          const dom_top = document.getElementById(dom_id).getBoundingClientRect().top
          if (dom_top < 250 && dom_top > 0) {
            that.topNavBaroIndex = i
          }
          if (scroll + windowHeight === scrollHeight) {
            that.topNavBaroIndex = that.topNavBar.length - 1
          }
        }
      },
      // 导航定位事件
      goTarget(id, index) {
        document.querySelector(id).scrollIntoView({
          behavior: 'smooth',
          block: 'center'
        })
        this.topNavBaroIndex = index
      },
      // 保存事件
      doSave() {
        this.validShowList = []
        const refArrays = []
        refArrays.push('goodsInfoRef')
        refArrays.push('goodsChannelRef')
        refArrays.push('goodsSkuRef')
        refArrays.push('goodsCommissionRef')
        refArrays.push('goodsParameterRef')
        refArrays.push('goodsOtherRef')
        // 表单校验
        const checkFailArrays = []
        refArrays.forEach(refKey => {
          const res = this.$refs[refKey].checkForm()
          if (!res) {
            checkFailArrays.push(refKey)
          }
        })
        if (checkFailArrays.length > 0) {
          return
        }
        // 先保存模板 后回调携带模板id保存商品信息
        this.$refs.goodsDetailRef.saveTemplate()
      },
      // 保存后处理
      doSaveAfterHandle() {
        const refArrays = []
        refArrays.push('goodsInfoRef')
        refArrays.push('goodsChannelRef')
        refArrays.push('goodsSkuRef')
        refArrays.push('goodsCommissionRef')
        refArrays.push('goodsParameterRef')
        refArrays.push('goodsOtherRef')
        // 表单组装
        const finalSubmitForm = {}
        refArrays.forEach(refKey => {
          const submitForm = this.$refs[refKey].submitForm()
          Object.assign(finalSubmitForm, submitForm)
        })

        finalSubmitForm.enterpriseId = this.getEnterpriseId()
        finalSubmitForm.goodsId = this.goodsId
        finalSubmitForm.goodsSyncHistoryId = this.goodsSyncHistoryId
        finalSubmitForm.anchorTemplateId = this.anchorTemplateId
        finalSubmitForm.detailTemplateId = this.detailTemplateId

        this.listLoading = true
        saveGoods(finalSubmitForm).then((response) => {
          this.listLoading = false
          if (response.isError) return
          this.resultForm.goodsId = response.data
          this.resultVisible = true
        })
      },
      // 添加验证展示信息
      addVaildShow(field) {
        const propArr = this.validShowList.map(item => item.prop)
        if (propArr.indexOf(field.prop) === -1) {
          this.validShowList.push(field)
        }
      },
      // 跳转
      doJump(element) {
        element.scrollIntoView({
          behavior: 'smooth',
          block: 'center'
        })
      },
      // 关闭页面事件
      doClose() {
        window.close()
      },
      // 查看商品事件
      doSeeDetail() {
        this.resultVisible = false
        this.$router.push({
          path: '/goods/edit/index',
          query: {
            goodsId: this.resultForm.goodsId,
            fromListPage: this.fromListPage,
            time: new Date().getTime()
          }
        })
      },
      // 新建商品事件
      doAdd() {
        this.resultVisible = false
        this.$router.push({
          path: '/goods/edit/index',
          query: {
            fromListPage: this.fromListPage,
            time: new Date().getTime()
          }
        })
        window.document.title = '新建' + (this.fromListPage === 30 ? '零售' : '批发') + '商品'
      }
    }
  }
</script>

<style lang="less" scoped>
  .circle-x-tab {
    padding-bottom: 70px;

    /deep/.el-checkbox__label {
      font-size: 16px;
    }

    /deep/.el-radio__label {
      font-size: 14px;
    }

    /deep/.el-checkbox__inner {
      width: 14px;
      height: 14px;
    }

    /deep/.el-checkbox__inner {
      width: 18px;
      height: 18px;
    }

    /deep/.form-diy .el-form-item {
      background: none;
    }

    /deep/.form-diy .el-form-item.none-mar-b {
      margin-bottom: 0 !important;
    }

    /deep/.form-diy .el-color-picker--medium .el-color-picker__trigger {
      width: 100px;
    }

    /deep/.form-diy .el-color-picker__empty,
    /deep/.form-diy .el-color-picker__icon {
      left: 80%;
    }

    /deep/.form-diy .el-form-item__label {
      font-size: 14px !important;
      font-weight: normal !important;
    }

    /deep/.form-diy .el-upload--picture-card {
      width: 100px;
      height: 100px;
      line-height: 100px;
    }

    /deep/.el-form-item {
      background: white;
    }

    /deep/.el-form-item .el-form-item {
      margin-bottom: 22px;
    }

    /deep/.one-label>.el-form-item__label {
      text-align: center;
      font-size: 16px;
      padding-top: 22px;
      color: #333;
      font-family: "微软雅黑", "Arial", "sans-serif";
    }

    /deep/.one-label>.el-form-item__content {
      padding: 20px 50px 20px 0;
      border-left: #F7F8FA 10px solid;

      .el-form-item__label {
        font-size: 14px;
      }
    }

    /deep/.el-form-item__content {
      font-size: 14px;

      .el-form-item__label {
        font-size: 18px;
        font-weight: normal;
      }
    }
  }

  .top-nav {
    position: sticky;
    // top: 50px;
    top: 0;
    left: 0;
    width: 100%;
    height: 60px;
    background: white;
    display: flex;
    align-items: center;
    justify-content: space-around;
    z-index: 999;
    box-shadow: 0 2px 6px #eee;

    .nav-item {
      cursor: pointer;
    }

    .nav-active {
      position: relative;
      color: #409eff;

      &::after {
        content: '';
        position: absolute;
        bottom: -20px;
        left: -15px;
        width: calc(100% + 30px);
        height: 2px;
        background-color: #409eff;
      }
    }
  }

  .bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 72px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: white;
    z-index: 999;
    box-shadow: 5px 1px 5px #cccccc;

    .el-button {
      width: 100px;
      height: 40px;
      line-height: 40px;
      padding: 0;
    }

    .el-button+.el-button {
      margin-left: 30px;
    }
  }

  .el-form-item__content {
    .el-button {
      padding: 0;
      height: 34px;
      width: 139px;
    }
  }

  .span-bar {
    padding: 0 50px;
  }

  .remove-btn {
    padding: 7px 6px !important;
  }

  .long-input {
    width: 80%;
  }

  .long-input-2 {
    width: 55%;
    margin-right: 5%;
  }

  .long-input-3 {
    width: 55%;
  }

  .short-input {
    width: 20%;
  }

  .short-input-2 {
    width: 25%;
  }

  .default-input {
    width: 50%;
  }

  .tips {
    color: gray;
    font-size: 12px;
    line-height: 1.2;
    padding-top: 5px;
  }

  .picture {
    width: 130px;
    height: 130px;
    display: block;
  }

  .pic-bar {
    position: relative;

    .close-icon {
      position: absolute;
      right: -30px;
      top: -11px;
      width: 31px;
      height: 40px;
      padding: 0 7px;
      cursor: pointer;
    }

    span {
      position: absolute;
      right: 0;
      bottom: 0;
      width: 100%;
      display: block;
      color: #fff;
      text-align: center;
      padding: 3px 0;
      background: rgba(0, 0, 0, 0.5);
      cursor: pointer;
    }
  }

  .pic-add {
    background: #fff;
    border: #d3d3d3 1px dashed;
    border-radius: 5px;
    padding: 0 45px;
  }
  .bottom-btn {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
  }
  .valid-show-box {
    position: fixed;
    top: 105px;
    right: 40px;
    width: 240px;
    border: solid 1px #E4E7ED;
    border-radius: 10px;
    background: white;
    overflow-y: auto;
    .box-head {
      background: lightgray;
      padding-left: 6px;
      font-weight: bold;
      height: 35px;
      padding-top: 7px;
      border-bottom: solid 1px #E4E7ED;
    }
    .box-body {
      max-height: 369px;
      overflow-y: auto;
      /deep/ .el-row {
        padding: 0 5px;
      }
      /deep/ .el-row:not(:last-child) {
        border-bottom: solid 1px #E4E7ED;
      }
      &::-webkit-scrollbar {
        width: 4px;
        height: 4px;
      }
      &::-webkit-scrollbar-thumb {
        border-radius: 5px;
        -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
        background: rgba(0,0,0,0.2);
      }
      &::-webkit-scrollbar-track {
        -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
        border-radius: 0;
        background: rgba(0,0,0,0.1);
      }
    }
  }
  /deep/ input[maxlength] {
    padding-right: 60px;
  }
</style>
